﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.WindowsAzure.StorageClient;
using Microsoft.WindowsAzure;
using System.Threading;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
using System.Drawing;

namespace Melos
{
	/**
	 * Generic class to handle ms azure blobs in a specific container
	 * currently, the container name is hard-coded; should be got from the constructor
	 */
    public class BlobHandler
    {
        CloudBlobContainer blobContainer;
        public const string containerName = "kepek";
        BinaryFormatter formatter = new BinaryFormatter();
        public BlobHandler(CloudStorageAccount sa)
        {
            getBlobContainer(sa);
        }
        public CloudBlobContainer getBlobContainer(CloudStorageAccount sa) {
            blobContainer = sa.CreateCloudBlobClient().GetContainerReference(containerName);
            blobContainer.CreateIfNotExist();
            /// Sets public access for the container
            blobContainer.SetPermissions(new BlobContainerPermissions() { PublicAccess = BlobContainerPublicAccessType.Blob });
            return blobContainer;
        }
        /**
         * Get a blob as stream 
         */
        public Stream getStream(String blobAddress) {
            Stream stream = new MemoryStream();
            blobContainer.GetBlobReference(blobAddress).DownloadToStream(stream);
            return stream;
        }
        /**
         * Put a stream into a blob
         * WARNING: stream may have to be rewound before this operation
         */
        public String putStream(Stream stream,String directory)
        {
            string key = Guid.NewGuid().ToString();
            string blobUrl = directory + "/" + key;
            CloudBlob blob = blobContainer.GetBlobReference(blobUrl);
            blob.UploadFromStream(stream);
            //Stream stream = new MemoryStream();
            blob.SetProperties(new BlobRequestOptions(){AccessCondition=AccessCondition.None});
            return blob.Uri.ToString();
        }
    }
}
